﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QLK.Database.DALs
{
    public class CategoryDAL
    {
        private ManageStoreDataContext db;

        public CategoryDAL()
        {
            db = new ManageStoreDataContext();
        }

        public List<Category> Cate_GetAll()
        {
            var categories = from cate in db.Categories
                             orderby cate.CategoryName
                             select cate;

            return categories.ToList<Category>();
        }

        public Category Cate_GetByID(int CateID)
        {
            Category categories = db.Categories.Single<Category>(cate => cate.CategoryID == CateID);
            return categories;
        }

        public bool Cate_Insert(Category Cates)
        {
            try
            {
                db.Categories.InsertOnSubmit(Cates);
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }

        }

        public bool Cate_DeleteByID(int CateID)
        {
            Category category = db.Categories.Single<Category>(cate => cate.CategoryID == CateID);

            if (category == null)
                return false;

            db.Categories.DeleteOnSubmit(category);

            try
            {
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }

        }

        public bool Cate_UpdateByID(Category  Cates)
        {
            Category category = db.Categories.Single<Category>(cate => cate.CategoryID == Cates.CategoryID);

            if (category == null)
                return false;

            category.CategoryName = Cates.CategoryName;

            try
            {
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public bool CategoryCheckDuplicateName(string CateName)
        {
            var Cate = from c in db.Categories
                       select c;
            if (Cate.ToList<Category>().Count == 0)
                return true;
            else
            {
                var cate = (from c in db.Categories
                            where c.CategoryName == CateName
                            select c).SingleOrDefault();
                if (cate == null)
                    return true;
                return false;
            }
        }

    }
}
